import 'dart:async';

import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:video_player/video_player.dart';

class VideoPlayerView extends StatefulWidget {
  const VideoPlayerView(
    this.url, {
    super.key,
    this.controller,
    this.height,
  });
  final String? url;
  final StreamController<bool>? controller;
  final double? height;

  @override
  State<VideoPlayerView> createState() => _VideoPlayerViewState();
}

class _VideoPlayerViewState extends State<VideoPlayerView> {
  late final VideoPlayerController controller;
  late final ChewieController chewieCtrl;
  StreamSubscription? subscription;

  @override
  void initState() {
    super.initState();
    _setup();
    subscription = widget.controller?.stream.listen((val) {
      if (val) {
        chewieCtrl.play();
      } else {
        chewieCtrl.pause();
      }
    });
  }

  void _setup() {
    if (widget.url == null) return;
    controller = VideoPlayerController.networkUrl(Uri.parse(widget.url!));
    chewieCtrl = ChewieController(
      videoPlayerController: controller,
      autoInitialize: true,
      autoPlay: false,
      allowMuting: false,
      showControlsOnInitialize: false,
    );
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, cons) {
      return AspectRatio(
        aspectRatio: widget.height != null
            ? cons.biggest.width / widget.height!
            : 16 / 9,
        child: Chewie(controller: chewieCtrl),
      );
    });
  }

  @override
  void dispose() {
    controller
      ..pause()
      ..dispose();
    chewieCtrl.dispose();
    subscription?.cancel();
    super.dispose();
  }
}
